package com.cnct.generic.dubbo.holder;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.cnct.generic.dubbo.strategy.RequireReferenceStrategy;
import com.cnct.generic.dubbo.utils.KeyGenerateUtil;
import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * 走注册中心方式
 *
 * @author wangzhen
 */
@Slf4j
@Component("registryRequireReferenceStrategy")
public class RegistryReferenConfig implements RequireReferenceStrategy {

    private ReferenceHolder referenceHolder;


    public RegistryReferenConfig(ReferenceHolder referenceHolder) {
        this.referenceHolder = referenceHolder;
    }

    @Override
    public ReferenceConfig requireReferenceConfig(ApplicationConfig application, RegistryConfig registry, String group, String url, String interfaceName, String version) {

        String key = KeyGenerateUtil.referenceKey(interfaceName, group, version);

        //从缓存中获取服务提供者的配置
        ReferenceConfig referenceConfig = referenceHolder.cache().getIfPresent(key);

        if (null == referenceConfig) {

            referenceConfig = referenceHolder.buildReferenceConfig(application, registry, group, version, interfaceName);

            //版本信息
            if (StringUtils.isNotEmpty(version)) {
                referenceConfig.setVersion(version);
            }
            referenceHolder.cache().put(key, referenceConfig);
        }
        return referenceConfig;
    }
}
